package com.bxait.toymail.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.bxait.com.to.es.SkuEsModel;
import com.bxait.toymail.search.config.ToyMailElasticSearchConfig;
import com.bxait.toymail.search.constant.EsConstant;
import com.bxait.toymail.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Chen
 * @description:
 * @ClassName ProductSaveServiceImpl
 * @create 2023-04-14 20:44
 * @Version 1.0
 */
@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource
    RestHighLevelClient restHighLevelClient;

    /*
     * @param skuEsModels 保存到es服务器上的模型数据
     * @==============History===============<br/>
     * @Description //   商品上架到es服务器上
     * @Date 2023/4/14 20:59
     * @Author <a href="qq:2277411582@qq.com">chen</a>
     * @return boolean
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 1、给es中建立索引。product，建立好映射关系。product-mapping.txt

        // 2.保存数据到es服务器
        // 创建批量操作es的请求
        BulkRequest bulkRequest = new BulkRequest();
        // 遍历需要上架的商品
        for (SkuEsModel skuEsModel : skuEsModels) {
            // 构造请求的对象,设置请求数据的索引
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            // 将需要保存的数据转换为JSON对象,保存到es中
            String esModelJson = JSON.toJSONString(skuEsModel);
            // 设置保存数据到es的id
            indexRequest.id(skuEsModel.getSkuId().toString());
            // 将数据转换成JSON进行保存
            indexRequest.source(esModelJson, XContentType.JSON);
            // 将请求添加到bulkRequest
            bulkRequest.add(indexRequest);
        }

        // 3.执行批量操作,操作es服务器
        BulkResponse response = restHighLevelClient.bulk(bulkRequest, ToyMailElasticSearchConfig.COMMON_OPTIONS);

        // 4.获取响应数据
        // 获取上架是否有异常
        boolean isFlag = response.hasFailures();
        List<String> collect = Arrays.stream(response.getItems()).map(item -> item.getId()).collect(Collectors.toList());
        log.info("商品上架完成：{}，返回数据：{}",collect,response.toString());

        // 5.返回商品上架的结果
        return isFlag;
    }
}
